import React, { Component } from 'react'
import { NavLink } from 'react-router-dom'
import './Index.scss'
import '../../components/text/index.css'
import axios from '../../components/axios'
import pubsub from 'pubsub-js'
import toTop from './js/toTop'
export default class index extends Component {
    constructor(props){
        super(props)
        this.state={
            data:[],
            len:1,
            num:!isNaN(this.props.location.pathname.split("/")[this.props.location.pathname.split("/").length-1])?this.props.location.pathname.split("/")[this.props.location.pathname.split("/").length-1]:1
        }
    }
    componentDidMount(){
        pubsub.publish("component","首页")
        axios("blog",{"limit":this.state.num}
        ).then(result=>{
            this.setState({data:result.data.resData,page:result.data.len});
        }).catch(err=>{
            console.log(err);
        })
    }
    post=(e)=>{
        this.setState({num:e.target.innerHTML},()=>{
            axios("blog",{"limit":this.state.num}
            ).then(result=>{
                this.setState({data:result.data.resData,page:result.data.len});
                toTop();
            }).catch(err=>{
                console.log(err);
            })
        })
    }
    render() {
        let page = this.state.page
        let arr=[]
        for(var i = 0;i<page;i++){
            arr[i]=""
        }
        return (
            <div className="inner">
                {this.state.data.map((item,index)=>{
                    function createMarkup() {
                        return { __html: item.text }
                    }
                    function MyComponent() {
                        return (
                            <p className="index-article-preview" dangerouslySetInnerHTML={createMarkup()}></p>
                        )
                    }
                    return (
                        <div className="index-article">
                            <h2 className="index-article-title"><NavLink to={`/content/${item.id}`}>{item.title}</NavLink></h2>
                            <p className="index-article-time">发表于 <span>{item.time}</span> | 更新于: <span>{item.changeTime}</span> | 分类于 <NavLink to={{pathname:"/search",state:{data:item.tags,type:"标签"}}}>{item.tags}</NavLink></p>
                            {MyComponent()}
                            <NavLink to={`/content/${item.id}`} className="index-article-post">阅读全文 » </NavLink>
                        </div>
                    )
                })}
                <nav className="index-nav">
                    <ul>
                        {arr.map((item,index)=>{
                            return(<li>
                                <NavLink to={"/index/"+(index+1)} onClick={this.post}>{index+1}</NavLink>
                            </li>)
                        })}
                    </ul>
                </nav>
            </div>
        )
    }
}
